<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * ebay线上产品管理
 */
class EbayProduct extends CI_Controller{
    
	function __construct(){
		parent::__construct();
		$this->load->model('Function_m','fun');
		$this->load->model('EbayProduct_m','m');
        $this->pageSize =$this->config->item('pagenum');
    }
    
    function ajaxbutton(){
		$action = $other = $this->input->get('op');
		switch($action){
			case "getRateDetail":
                $this->getRateDetail();
				break; 
            case "reviseRateInfo":
                $this->reviseRateInfo();
            break;
            case "addMoneyRate":
                $this->addMoneyRate();
            break;
            case "showEditProducts":
                $this->showEditProducts();
            break;
            case "saveReviseProduct":
                $this->saveReviseProduct();
            break;
            case "saveEditShippingFee":
                $this->saveEditShippingFee();
            break;
            case "showEditShipingFee":
                $this->showEditShipingFee();
            case "reviseOnlineProduct":
                $this->reviseOnlineProduct();
            break;
		}
	}
    //列表商品列表
    public function productList(){
		$nowpage = $this->input->get("pageid");
        if ($nowpage == "") $nowpage = 1;
        $where = " ";
		if($this->input->get_post('webname')){
			$webname = $this->input->get_post('webname');
			 $where.=" AND webname ='".$webname."'";
			 $this->tpl->assign("webnamevalue", $this->input->get_post('webname'));
		}


		$starttime = trim($this->input->get('starttime'));
		if ($starttime) {
			$times = $starttime . " 00:00:00";
			$timess = strtotime($times);
			$where .= " AND (intime >= '" . $timess . "')";
			$this->tpl->assign("starttime", $starttime);
		}

		$endtime = trim($this->input->get('endtime'));
		if ($endtime) {
			$times = $endtime . " 23:59:59";
			$endtimes = strtotime($times);
			$where .= " AND (intime <= '" . $endtimes. "')";
			$this->tpl->assign("endtime", $endtime);
		}
		if ($this->input->get_post('kw')) {
			$kw = trim($this->input->get_post('kw'));
			$where .= " AND (sku like '%" . $kw. "%' or name like '%" . $kw. "%')";
			$this->tpl->assign("kw", $kw);
		}

		$list = $this->fun->getalllist("db_ebay_productlist ", $where, $nowpage, 0, $this->pageSize);
		foreach($list["list"] as $key=>$rs){
		      $shippinginfo=json_decode($rs['shipping_info'],true);
			 $list["list"][$key]['name'] = stripslashes($rs['name']);
             $list["list"][$key]['shipping_fee'] =$shippinginfo[0]['ShippingServiceCost'];
             $list["list"][$key]['shipping_more_fee'] =$shippinginfo[0]['ShippingServiceAdditionalCost'];
			 $list["list"][$key]['waittime'] =date("Y-m-d H:i:s",$rs['intime']);
		}
		$webname = $this->fun->getdatabaseslist("db_ebay_productlist","","DISTINCT webname ");
		$this->tpl->assign("webname", $webname);
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
		$this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("productlist", $list["list"]);
        $this->tpl->display("EbayProduct/ebayProductList.tpl");
    }
     
    
    function showEditProducts(){
		$id = $this->input->post('id');
		$id =trim($id,",");
		$rsdb = $this->fun->getdatabaseslist('db_ebay_productlist'," AND id in ($id)","*"," order by field(id,$id)");
		if($rsdb){
			$html="";
			foreach($rsdb as $key=>$data){
                $rsdb[$key]['shipping_types']=json_decode($data['shipping_info'],true);
			}
		}
        $shiptimes=array(1,2,3,4,5,10,15,20,30);
        $this->tpl->assign('shiptimes',$shiptimes);
		$this->tpl->assign("datalist",$rsdb);
        $data=$this->tpl->fetch('EbayProduct/editStock.tpl');
        echo $data;  
    }
    
    public function showEditShipingFee(){
		$id = $this->input->post('id');
		$id =trim($id,",");
		$edit_list = $this->fun->getdatabaseslist('db_ebay_productlist'," AND id in ($id)","*"," order by field(id,$id)");
        $textareainfo='';$shipingtypes=array();
		if($edit_list){
			foreach($edit_list as $key=>$rs){
                $shipingtypes=array_merge($shipingtypes,json_decode($rs['shipping_info'],true));
                $textareainfo.="itemid:".$rs['product_id'].",sku:".$rs['sku']."\r\n";
			}
            $currency=$edit_list[0]['currency'];
		}
        $currency_count=count(array_unique(array_column($edit_list,'currency')));
        
        $shipingtype_arr=array_unique(array_column($shipingtypes,'ShippingService'));
        $shipingtypes_str=implode('|',$shipingtype_arr);
        $tpl_data=array('shipingtypes'=>$shipingtype_arr,'shipingtypes_str'=>$shipingtypes_str,'currency'=>$currency,'currency_count'=>$currency_count);
        //$itemids=implode('|',array_unique(array_column($edit_list,'product_id')));
        $itemids=implode(',',array_unique(array_column($edit_list,'id')));
        dump($itemids);
        $shiptimes=array(1,2,3,4,5,10,15,20,30);
        $this->tpl->assign('textareainfo',$textareainfo);
        $this->tpl->assign('itemids',$itemids);
        $this->tpl->assign('shiptimes',$shiptimes);
		$this->tpl->assign("datalist",$edit_list);
        $this->tpl->assign($tpl_data);
        $data=$this->tpl->fetch('EbayProduct/editShippingFee.tpl');
        echo $data; 
    }
    
    public function saveEditShippingFee(){
        $dataids=$_POST['dataids'];$shipingtypes=$_POST['shipingtypes'];$region=$_POST['region'];$location=$_POST['location'];$shipday=$_POST['shipday'];
        $shipping_one_fee=$_POST['shipping_fee'];$shipping_more_fee=$_POST['shipping_more_fee'];
        $shippingtypes=explode("|",$shipingtypes);
        $shipping_arr=array();
        for($i=0;$i<count($shippingtypes);$i++){
            $shipping_fees=array();
            if($shipping_one_fee[$i]!==''){
                //$shipping_fees['ShippingService']=$shippingtypes[$i];
                $shipping_fees['ShippingServiceCost']=$shipping_one_fee[$i];
            }
            if($shipping_more_fee[$i]!==''){
                //$shipping_fees['ShippingService']=$shippingtypes[$i];
                $shipping_fees['ShippingServiceAdditionalCost']=$shipping_more_fee[$i];
            }
            if($shipping_one_fee[$i]!=='' || $shipping_more_fee[$i]!==''){
                $shipping_arr[$shippingtypes[$i]]=$shipping_fees;
            }
        }
        if(!empty($region)){
            $save_data['region']=$region;
        }
        if(!empty($location)){
            $save_data['location']=$location;
        }
        if(!empty($shipday)){
            $save_data['shipday']=$shipday;
        }
        if(count($shipping_arr)>0){
            $save_data['shipping_fee']=$shipping_arr;
        }
        dump($save_data);
        if(count($save_data)>0){
            $save_data=array("updateShipping"=>json_encode($save_data),"isupload"=>0);
            $this->db->update('db_ebay_productlist',$save_data,"id in(".$dataids.")");//批量更新  
            //echo $this->db->last_query(); 
            $history_url=$_SERVER['HTTP_REFERER'];
            echo "保存成功，我们稍后将更新至线上,请<a href='$history_url'>返回上页</a>"; 
        }
    }

    public function saveReviseProduct(){
        $data_ids=$_POST['id'];
        $skus=$_POST['sku'];$titles=$_POST['product_name'];$is_open=$_POST['is_open'];$quantity=$_POST['quantity'];$price=$_POST['price'];
        $ship_to=$_POST['ship_to'];$max_ship_day=$_POST['max_ship_day'];
        $data_id_str=implode(',',$data_ids);
        $old_products=$this->fun->getdatabaseslist('db_ebay_productlist'," AND id in ($data_id_str)");
        $sourcedatas=array();
        foreach($old_products as $key=>$source_info){
            $sourcedatas[$source_info['id']]=$source_info;
        }
        
        $up_list=$reviseinfo=array();
        foreach($data_ids as $key=>$dataid){
            $reviseinfo=array();
            if($skus[$key]!=$sourcedatas[$dataid]['sku']){
                $reviseinfo['SKU']=$skus[$key];
            }
            if($titles[$key]!=$sourcedatas[$dataid]['name']){
                $reviseinfo['Title']=$titles[$key];
            }
            if($is_open[$key]!=$sourcedatas[$dataid]['is_open']){
                $reviseinfo['is_open']=$is_open[$key];
                if($is_open[$key]=='Ended'){
                    $reviseinfo['quantity']=0;
                }
            }
            if($quantity[$key]!=$sourcedatas[$dataid]['quantity']){
                if($is_open[$key]=='Ended'){
                    $quantity[$key]=0;
                }
                $reviseinfo['quantity']=$quantity[$key];
            }
            if($price[$key]!=$sourcedatas[$dataid]['price']){
                $reviseinfo['price']=$price[$key];
            }
            if($ship_to[$key]!=$sourcedatas[$dataid]['ship_to']){
                $reviseinfo['ship_to']=$ship_to[$key];
            }
            if($max_ship_day[$key]!=$sourcedatas[$dataid]['max_ship_day']){
                $reviseinfo['max_ship_day']=$max_ship_day[$key];
            }
            if(count($reviseinfo)>0){
                $save_data=array("id"=>$dataid,"updateData"=>json_encode($reviseinfo),"isupload"=>0);
                $up_list[]=$save_data;
            }       
        }

        if(count($up_list)>0){
            $this->db->update_batch('db_ebay_productlist', $up_list, 'id');//批量更新  
            //echo $this->db->last_query(); 
            $history_url=$_SERVER['HTTP_REFERER'];
            echo "修改成功，我们稍后将更新至线上,请<a href='$history_url'>返回上页</a>"; 
        }
        
    }
    
    
    //修订商品信息
    public function reviseOnlineProduct(){
        $needup_datas=$this->fun->getdatabaseslist('db_ebay_productlist'," AND isupload=0 group by product_id");
        foreach($needup_datas as $key=>$reviseinfo){
            $shopinfo = $this->fun->getdatabasesdetail("d_shop","and id={$reviseinfo['shopid']} and amazonkey<>''");//获取店铺token  
            $shopid=$shopinfo['id'];
            $name=$shopinfo['name'];
            $data=json_decode($shopinfo['amazonkey'],true);
            $devID=$data['ebaydevid'];
            $userToken=$data['ebayusertoken'];
            $appID=$data['ebayappid'];
            $certID=$data['ebaycertid'];
            $siteID=$data['ebaysiteid'];
            $compatabilityLevel=$data['ebaycompatabilitylevel'];
            $this->m->apiUpdateShipping($data, $devID, $appID, $certID, $compatabilityLevel, $siteID,$shopid,$reviseinfo);   
        }
        
        $needup_datas=$this->fun->getdatabaseslist('db_ebay_productlist'," AND isupload=0");//and id=245102
        foreach($needup_datas as $key=>$reviseinfo){
            $shopinfo = $this->fun->getdatabasesdetail("d_shop","and id={$reviseinfo['shopid']} and amazonkey<>''");//获取店铺token  
            $shopid=$shopinfo['id'];
            $name=$shopinfo['name'];
            $data=json_decode($shopinfo['amazonkey'],true);
            $devID=$data['ebaydevid'];
            $userToken=$data['ebayusertoken'];
            $appID=$data['ebayappid'];
            $certID=$data['ebaycertid'];
            $siteID=$data['ebaysiteid'];
            $compatabilityLevel=$data['ebaycompatabilitylevel'];
            echo "<br /><br />开始更新店铺{$shopinfo['name']}商品参数<br />";
            $this->m->apiReviseProducts($data, $devID, $appID, $certID, $compatabilityLevel, $siteID,$shopid,$reviseinfo);   
        }
        echo "调整更新完成";
    }
    
    //上架新商品
    public function addNewProduct(){
        
        
        $this->tpl->display("EbayProduct/addNewProduct.tpl");   
    }
    
    //下载店铺商品列表
    public function downOnLineProductList(){
        ini_set('max_execution_time', '0');
        $nowpage = $this->input->get("pageid");
        if ($nowpage == "") $nowpage = 1;
        $shopid=$this->input->get("shopid");
        if($shopid>0){
            $row = $this->db->get_where("d_shop","id={$shopid} and amazonkey<>''")->result_array();//获取店铺token    
        }else{
            $row = $this->db->get_where("d_shop","platfrom=1 and del_flag=0 and amazonkey<>''")->result_array();//获取店铺token       
        }
        foreach ($row as $v) {
            //$v=$row[3];
            $shopid=$v['id'];
            $name=$v['name'];
            $data=json_decode($v['amazonkey'],true);
            $data['pageid']=$nowpage;
            $devID=$data['ebaydevid'];
            $userToken=$data['ebayusertoken'];
            $appID=$data['ebayappid'];
            $certID=$data['ebaycertid'];
            $siteID=$data['ebaysiteid'];
            $compatabilityLevel=$data['ebaycompatabilitylevel'];
            echo "<br /><br />开始导入店铺{$v['name']}商品列表<br />";
            $this->m->importProductList($data, $devID, $appID, $certID, $compatabilityLevel, $siteID,$shopid,$v['name']);    
        }
            
        echo "<br />商品导入完成；<br />";
    }
    
    
    //获取ebay分类
    public function getEbayCategories(){
        
    }
    
    //发布产品至线上
    public function publishGoodsToLine(){
        
    }
    
    
}
?>